<template>
  <div class="container">
  	<div class="userinfo" @click="login">
  	  <img :src="userinfo.avatarUrl">
  	  <p>{{userinfo.nickName}}</p>
  	</div>
  	<year-progress></year-progress>
  	<button v-if="userinfo.openId" @click="scanBook" class="btn">添加图书</button>
    <button
      open-type="getUserInfo"
      >授权</button>
  </div>
</template>

<script>
import qcloud from 'wafer2-client-sdk'
import {showSuccess, post, showModal} from '@/utils/util'
import config from '@/config/config'
import YearProgress from '@/components/YearProgress'
export default {
  data () {
    return {
      userinfo: {
        avatarUrl: '../../../static/img/unlogin.png',
        nickName: '点击登录'
      }
    }
  },
  components: {
    YearProgress
  },
  methods: {
    async addBook (isbn) {
      const res = await post('/weapp/addbook', {
        isbn,
        openid: this.userinfo.openId
      })
      showModal('添加成功', res.title)
    },
    scanBook () {
      wx.scanCode({
        success: (res) => {
          if (res.result) {
            this.addBook(res.result)
          }
        }
      })
    },
    login () {
      let user = wx.getStorageSync('userInfo')
      const self = this
      if (!user) {
        qcloud.setLoginUrl(config.loginUrl)
        qcloud.login({
          success: function (userInfo) {
            qcloud.request({
              url: config.userUrl,
              login: true,
              success (userRes) {
                showSuccess('登录成功')
                wx.setStorageSync('userInfo', userRes.data.data)
                self.userinfo = userRes.data.data
              }
            })
          }

        })
      }
    }
    // login () {
    //   let user = wx.getStorageSync('userInfo')
    //   const that = this
    //   if (!user) {
    //     qcloud.setLoginUrl(config.loginUrl)
    //     qcloud.login({
    //       success: function (userInfo) {
    //         // console.log('登录成功', userInfo)
    //         showSuccess('登录成功')
    //         wx.setStorageSync('userInfo', userInfo)
    //         that.userinfo = userInfo
    //       },
    //       fail: function (err) {
    //         console.log('登录失败', err)
    //       }
    //     })
    //   }
    // }
  },
  created () {
    let userinfo = wx.getStorageSync('userInfo')
    if (userinfo) {
      this.userinfo = userinfo
    }
  }
}
</script>

<style lang='scss'>
.container{
  padding:0 30rpx;

}  
.userinfo {
  margin-top:100rpx;
  text-align:center;
  img{
    width: 150rpx;
    height:150rpx;
    margin: 20rpx;
    border-radius: 50%;
  }
}
</style>
